package com.hengpeng.itfin.domain.partner.fund;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.hengpeng.common.exception.ServiceResult;
import com.hengpeng.common.util.DateTimeUtil;
import com.hengpeng.common.util.MoneyUtil;
import com.hengpeng.common.util.WebClientUtil;
import com.hengpeng.itfin.constants.MSConstants;
import com.hengpeng.itfin.domain.imprest.ImprestProcessorFactory;
import com.hengpeng.itfin.domain.partner.AbstractPartnerProcessor;
import com.hengpeng.itfin.domain.vo.AccountLogVO;
import com.hengpeng.itfin.service.ServiceFactory;
import com.hengpeng.itfinbase.constants.PaymentConstants;
import com.hengpeng.itfinbase.constants.RespCodeConstants;
import com.hengpeng.itfinbase.constants.RespCodeConstants.CommonCode;
import com.hengpeng.itfinbase.en.SubAccountType;
import com.hengpeng.itfinbase.en.TradeMode;
import com.hengpeng.itfinbase.en.TransType;
import com.hengpeng.itfinbase.message.ResponseMessage;
import com.hengpeng.itfinbase.message.partner.AddBidInfoRequest;
import com.hengpeng.itfinbase.message.partner.AddBidInfoResponse;
import com.hengpeng.itfinbase.message.partner.BindCardRequest;
import com.hengpeng.itfinbase.message.partner.CashRequestMsg;
import com.hengpeng.itfinbase.message.partner.CorpOpenRequestMsg;
import com.hengpeng.itfinbase.message.partner.CorpRegisterQueryRequest;
import com.hengpeng.itfinbase.message.partner.CreditAssignRequest;
import com.hengpeng.itfinbase.message.partner.CreditAssignResponse;
import com.hengpeng.itfinbase.message.partner.DrawReconciliationRequestMsg;
import com.hengpeng.itfinbase.message.partner.DrawReconciliationResponseMsg;
import com.hengpeng.itfinbase.message.partner.InvestInfoRequestMsg;
import com.hengpeng.itfinbase.message.partner.InvestInfoResponseMsg;
import com.hengpeng.itfinbase.message.partner.LoansRequest;
import com.hengpeng.itfinbase.message.partner.LoansResponse;
import com.hengpeng.itfinbase.message.partner.ModifyRequest;
import com.hengpeng.itfinbase.message.partner.NotifyRequestMsg;
import com.hengpeng.itfinbase.message.partner.NotifyResponseMsg;
import com.hengpeng.itfinbase.message.partner.OpenRequestMsg;
import com.hengpeng.itfinbase.message.partner.PayRequestMsg;
import com.hengpeng.itfinbase.message.partner.PayResponseMsg;
import com.hengpeng.itfinbase.message.partner.QueryAcctsRequestMsg;
import com.hengpeng.itfinbase.message.partner.QueryAcctsResponseMsg;
import com.hengpeng.itfinbase.message.partner.QueryAcctsResponseMsg.AcctsAccount;
import com.hengpeng.itfinbase.message.partner.QueryBalanceRequest;
import com.hengpeng.itfinbase.message.partner.QueryBalanceResponse;
import com.hengpeng.itfinbase.message.partner.QueryCardInfoRequestMsg;
import com.hengpeng.itfinbase.message.partner.QueryCardInfoResponseMsg;
import com.hengpeng.itfinbase.message.partner.QueryTransDetailRequest;
import com.hengpeng.itfinbase.message.partner.QueryTransDetailResponse;
import com.hengpeng.itfinbase.message.partner.QueryTransStatRequest;
import com.hengpeng.itfinbase.message.partner.QueryTransStatResponse;
import com.hengpeng.itfinbase.message.partner.ReconciliationRequestMsg;
import com.hengpeng.itfinbase.message.partner.ReconciliationResponseMsg;
import com.hengpeng.itfinbase.message.partner.RepaymentRequestMsg;
import com.hengpeng.itfinbase.message.partner.RepaymentResponseMsg;
import com.hengpeng.itfinbase.message.partner.SaveReconciliationRequestMsg;
import com.hengpeng.itfinbase.message.partner.SaveReconciliationResponseMsg;
import com.hengpeng.itfinbase.message.partner.TenderCancleRequest;
import com.hengpeng.itfinbase.message.partner.TenderCancleResponse;
import com.hengpeng.itfinbase.message.partner.TransferRequest;
import com.hengpeng.itfinbase.message.partner.TransferResponse;
import com.hengpeng.itfinbase.message.partner.TrfReconciliationRequestMsg;
import com.hengpeng.itfinbase.message.partner.TrfReconciliationResponseMsg;
import com.hengpeng.itfinbase.message.partner.UsrUnFreezeRequest;
import com.hengpeng.itfinbase.message.partner.UsrUnFreezeResponse;
import com.hengpeng.itfinbase.persist.Account;
import com.hengpeng.itfinbase.persist.AccountLog;
import com.hengpeng.itfinbase.persist.AccountLogReport;
import com.hengpeng.itfinbase.persist.Partner;
import com.hengpeng.itfinbase.persist.PaymentProvider;
import com.hengpeng.itfinbase.persist.UserBankCard;

public class FundProcessorImpl extends AbstractPartnerProcessor {
    public FundProcessorImpl(ServiceFactory context, Partner partner) {
        super(context, partner);
    }

    @Override
    public QueryTransDetailResponse queryTransDetail(QueryTransDetailRequest request) {
        return null;
    }

    @Override
    public CreditAssignResponse packageCreditAssign(CreditAssignRequest reqeust) {
        CreditAssignResponse response = new CreditAssignResponse();
        response.setOrdId(reqeust.getOrdId());
        response.setBuyCustId(reqeust.getBuyCustId());
        response.setFee(reqeust.getFee());
        ServiceResult<String> result = serviceFactory.getAssignService().dealAssignResult(response);
        response.setRespCode(result.getCode());
        response.setRespDesc(result.getMessage());
        if (result.getIsSuccess()) {
            response.setOrderFormContent("转让成功");
        } else {
            response.setOrderFormContent(result.getMessage());
        }
        return response;
    }

    @Override
    public InvestInfoResponseMsg packageInitiativeTenderRequest(InvestInfoRequestMsg request) {
        InvestInfoResponseMsg response = new InvestInfoResponseMsg();
        response.setOrdId(request.getInvestInfoId().toString());
        response.setFreezeTrxId(request.getInvestInfoId().toString());
        response.setRespCode(CommonCode.TRANS_SUC);
        ServiceResult<String> result = serviceFactory.getInvestInfoService().dealInvestResult(response);
        if (result.getIsSuccess()) {
            response.setOrderFormContent("投标成功");
        } else {
            response.setOrderFormContent(result.getMessage());
        }
        return response;
    }

    @Override
    public UsrUnFreezeResponse usrUnFreeze(UsrUnFreezeRequest request) {
        UsrUnFreezeResponse response = new UsrUnFreezeResponse();
        response.setOrdId(request.getOrdId());
        return response;
    }

    @Override
    public AddBidInfoResponse addBidInfo(AddBidInfoRequest request) {
        AddBidInfoResponse response = new AddBidInfoResponse();
        response.setProId(request.getProId());
        return response;
    }

    @Override
    public LoansResponse loans(LoansRequest request) {
        LoansResponse response = new LoansResponse();
        response.setOrdId(request.getOrdId());
        return response;
    }

    @Override
    public ResponseMessage batchRepaymentRequest(RepaymentRequestMsg request) {
        RepaymentResponseMsg response = new RepaymentResponseMsg();
        try {
            String merPriv = request.isPlatfor() ? MSConstants.CHAR_ONE : MSConstants.CHAR_ZERO;
            response.setBatchId(request.getBatchId());
            response.setProId(request.getProId());
            response.setMerPriv(merPriv);
            response.setRepaymentPlanId(Long.parseLong(request.getRepaymentPlanId()));
            ServiceResult<String> result = serviceFactory.getRepaymentService().dealBatchRepaymentResult(response);
            response.setRespCode(result.getCode());
            response.setRespDesc(result.getMessage());
        } catch (Exception e) {
            logger.error(e);
        }
        return response;
    }

    @Override
    public ResponseMessage repaymentRequest(RepaymentRequestMsg request) {
        RepaymentResponseMsg response = new RepaymentResponseMsg();
        response.setTransAmt(request.getTransAmt());
        response.setOrdId(request.getOrdId());
        response.setMerPriv(request.getMerPriv());
        response.setOutCustId(request.getOutCustId());
        response.setRepaymentPlanId(Long.parseLong(request.getRepaymentPlanId()));
        ServiceResult<String> result = serviceFactory.getRepaymentService().dealRepaymentResult(response);
        response.setRespCode(result.getCode());
        response.setRespDesc(result.getMessage());
        return response;
    }

    @Override
    public ResponseMessage queryBalanceBgRequest(QueryBalanceRequest request) {
        QueryBalanceResponse response = new QueryBalanceResponse();
        Account account = serviceFactory.getAccountService().getAccount(request.getUserId());
        if (account != null) {
            Long aval = account.getBaseMoney() - account.getFreezeMoney();
            response.setAvlBal(MoneyUtil.convertFenToYuan(aval));
            response.setFrzBal(MoneyUtil.convertFenToYuan(account.getFreezeMoney()));
            response.setAcctBal(MoneyUtil.convertFenToYuan(account.getBaseMoney()));
            response.setUsrCustId(account.getTrustAccountId());
        } else {
            response.setAvlBal("0");
            response.setFrzBal("0");
            response.setAcctBal("0");
        }
        return response;
    }

    @Override
    public ReconciliationResponseMsg reconciliation(ReconciliationRequestMsg request) {
        ReconciliationResponseMsg response = new ReconciliationResponseMsg();
        response.setTotalItems("0");
        return response;
    }

    @Override
    public TrfReconciliationResponseMsg trfReconciliation(TrfReconciliationRequestMsg request) {
        TrfReconciliationResponseMsg response = new TrfReconciliationResponseMsg();
        response.setTotalItems("0");
        return response;
    }

    @Override
    public QueryTransStatResponse queryTransStat(QueryTransStatRequest request) {
        QueryTransStatResponse response = new QueryTransStatResponse();
        response.setTransStat("U");
        return response;
    }

    @Override
    public QueryCardInfoResponseMsg queryCardInfo(QueryCardInfoRequestMsg request) {
        QueryCardInfoResponseMsg msg = new QueryCardInfoResponseMsg();
        List<UserBankCard> list = serviceFactory.getDaoFactory().getUserBankCardDao()
                .findUserBankCardByUserName(request.getUserName());
        msg.setUserBankCardlist(list);
        return msg;
    }

    @Override
    public QueryAcctsResponseMsg queryAcctsRequest(QueryAcctsRequestMsg request) {
        QueryAcctsResponseMsg response = new QueryAcctsResponseMsg();
        response.setMerCustId(request.getMerCustId());
        Account account = serviceFactory.getDaoFactory().getStaticJDBCDao().getPlatformAccount();
        List<AcctsAccount> details = new ArrayList<AcctsAccount>();
        response.setAcctDetails(details);
        AcctsAccount acc = new AcctsAccount();
        Long money = account.getBaseMoney() - account.getFreezeMoney();
        acc.setAvlBal(MoneyUtil.convertFenToYuan(money));
        acc.setFrzBal(MoneyUtil.convertFenToYuan(account.getFreezeMoney()));
        acc.setAcctBal(MoneyUtil.convertFenToYuan(account.getBaseMoney()));
        acc.setAcctType(account.getSubAccountType().getText());
        acc.setSubAcctId(account.getSubAccountId());
        details.add(acc);

        String[] spedtString = new String[] { TransType.LOAN_FEE.toString(), TransType.CREDITASSIGN_FEE.toString(),
                TransType.IMPREST_FEE.toString(), TransType.DRAW_FEE.toString(), TransType.ADDMONEY.toString() };
        AccountLogReport spedt = serviceFactory.getDaoFactory().getStaticJDBCDao().getPlatformSpedtAccount(spedtString);// 获取费率账户资金

        String curDate = DateTimeUtil.formatToStr(new Date(), "yyyy-MM-dd");// 当天日期
        Date start = DateTimeUtil.formatToDate(curDate, "yyyy-MM-dd");
        String[] transType = new String[] { TransType.CREDITASSIGN_FEE.toString(), TransType.LOAN_FEE.toString(),
                TransType.DRAW_FEE.toString(), TransType.IMPREST_FEE.toString(), TransType.ADDMONEY.toString() };
        List<AccountLogVO> list = serviceFactory.getDaoFactory().getStaticJDBCDao()
                .getPlatAccountTrade(start, new Date(), transType);
        for (AccountLog accountLog : list) {
            if (accountLog.getTradeMode().equals(TradeMode.SUBTRACT)) {
                spedt.setTransMoney(spedt.getTransMoney() + accountLog.getMoney());
            }
            if (accountLog.getTradeMode().equals(TradeMode.ADD)) {
                spedt.setTransMoney(spedt.getTransMoney() - accountLog.getMoney());
            }
        }
        AcctsAccount spedtAcc = new AcctsAccount();
        spedtAcc.setAvlBal(MoneyUtil.convertFenToYuan(spedt.getTransMoney()));
        spedtAcc.setFrzBal("0");
        spedtAcc.setAcctBal(MoneyUtil.convertFenToYuan(spedt.getTransMoney()));
        spedtAcc.setAcctType(SubAccountType.SPEDT.getText());
        spedtAcc.setSubAcctId("SDT000001");
        details.add(spedtAcc);
        return response;
    }

    @Override
    public ResponseMessage packagePayRequest(PayRequestMsg request) {
        PayResponseMsg response = new PayResponseMsg();
        PaymentProvider provider = serviceFactory.getPayService().findProviderById(request.getProviderId());
        if (provider != null) {
            ImprestProcessorFactory.getProcessor(serviceFactory, provider).payRequest(request, response);
        } else {
            response.setRespCode(PaymentConstants.PAYMENT_TRANSMESSAGE_ERRCODE_NOPROVIDER);
            response.setRespDesc(PaymentConstants.PAYMENT_TRANSMESSAGE_ERRMSG_NOPROVIDER);
        }
        return response;
    }

    @Override
    public NotifyResponseMsg payNotify(NotifyRequestMsg request) {
        NotifyResponseMsg response = new NotifyResponseMsg();
        try {
            request.setParameter((WebClientUtil.readUrlParameterToMap(request.getParamString())));
            PaymentProvider provider = serviceFactory.getPayService().findProviderById(request.getProviderId());
            ImprestProcessorFactory.getProcessor(serviceFactory, provider).payNotify(request, response);
            return response;
        } catch (Exception e) {
            logger.error(e);
            response.setRespCode(RespCodeConstants.CommonCode.TRANS_FAIL);
            response.setRespDesc(RespCodeConstants.CommonCode.TRANS_FAIL_MSG);
            return response;
        }
    }

    @Override
    public SaveReconciliationResponseMsg saveReconciliation(SaveReconciliationRequestMsg request) {
        SaveReconciliationResponseMsg response = new SaveReconciliationResponseMsg();
        return response;
    }

    @Override
    public DrawReconciliationResponseMsg drawReconciliation(DrawReconciliationRequestMsg request) {
        DrawReconciliationResponseMsg response = new DrawReconciliationResponseMsg();
        return response;
    }

    @Override
    public ResponseMessage packageOpenRequest(OpenRequestMsg request) {
        return null;
    }

    @Override
    public NotifyResponseMsg openNotify(NotifyRequestMsg request) {
        return null;
    }

    @Override
    public ResponseMessage packageCorpOpenRequest(CorpOpenRequestMsg request) {
        return null;
    }

    @Override
    public NotifyResponseMsg corpOpenNotify(NotifyRequestMsg request) {
        return null;
    }

    @Override
    public ResponseMessage queryCorpOpenRequest(CorpRegisterQueryRequest request) {
        return null;
    }

    @Override
    public NotifyResponseMsg bindCardNotify(NotifyRequestMsg request) {
        return null;
    }

    @Override
    public NotifyResponseMsg batchRepaymentNotify(NotifyRequestMsg request) {
        return null;
    }

    @Override
    public NotifyResponseMsg repaymentNotify(NotifyRequestMsg request) {
        return null;
    }

    @Override
    public NotifyResponseMsg initiativeTenderNotify(NotifyRequestMsg request) {
        return null;
    }

    @Override
    public TransferResponse packageTransferRequest(TransferRequest request) {
        return null;
    }

    @Override
    public NotifyResponseMsg transferNotify(NotifyRequestMsg request) {
        return null;
    }

    @Override
    public ResponseMessage packageModifyRequest(ModifyRequest request) {
        return null;
    }

    @Override
    public ResponseMessage packageBindCardRequest(BindCardRequest request) {
        return null;
    }

    @Override
    public ResponseMessage packageDrawRequest(CashRequestMsg request) {
        return serviceFactory.getDrawingService().drawRequest(request);
    }

    @Override
    public NotifyResponseMsg drawNotify(NotifyRequestMsg request) {
        return null;
    }

    @Override
    public NotifyResponseMsg loansNotify(NotifyRequestMsg request) {
        return null;
    }

    @Override
    public TenderCancleResponse tenderCancle(TenderCancleRequest request) {
        return null;
    }

    @Override
    public NotifyResponseMsg usrUnFreezeNotify(NotifyRequestMsg request) {
        return null;
    }

    @Override
    public NotifyResponseMsg creditAssignNotify(NotifyRequestMsg request) {
        return null;
    }
}
